<template>
  <div class="app-container">
    <el-row justify="space-between">
      <el-col :span="20">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="任务名称" prop="taskName">
            <el-input
              v-model="queryParams.taskName"
              placeholder="请输入项目名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4" >
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:subject:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:subject:export']"
            >导出</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-table border v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column label="任务ID" align="center" prop="taskId" width="140">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
          >{{scope.row.taskId}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="70">
        <template slot-scope="scope">
          <el-tag  type="success">{{scope.row.status}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="任务名称" align="center" prop="taskName" width="140">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
          >{{scope.row.taskName}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="desp" width="220" />
      <el-table-column label="负责人" align="center" prop="headUser" width="140">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <el-tag effect="plain" :key="index" v-for="(item,index) in scope.row.headUsers">{{item.nickName}}</el-tag>
            <div slot="reference" class="name-wrapper">
              <el-tag v-if="scope.row.headUsers[0]" effect="plain">{{scope.row.headUsers[0].nickName}}</el-tag>
              <el-tag v-if="scope.row.headUsers[1]" effect="plain">{{scope.row.headUsers[1].nickName}}</el-tag>
              <span v-if="scope.row.headUsers.length > 2">...</span>
            </div>

          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="订阅人" align="center" prop="copyUser" width="140">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <el-tag effect="plain" :key="index" v-for="(item,index) in scope.row.copyUsers">{{item.nickName}}</el-tag>
            <div slot="reference" class="name-wrapper">
              <el-tag v-if="scope.row.copyUsers[0]" effect="plain">{{scope.row.copyUsers[0].nickName}}</el-tag>
              <el-tag v-if="scope.row.copyUsers[1]" effect="plain">{{scope.row.copyUsers[1].nickName}}</el-tag>
              <span v-if="scope.row.copyUsers.length > 2">...</span>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="立项时间" align="center" prop="fireDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.fireDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="要求完成时间" align="center" prop="demandDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.demandDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="ddate" width="120" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.ddate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            :disabled="canEdit(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row) "
            :disabled="canEdit(scope.row)"
            v-hasPermi="['system:task:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="模板名称" prop="subjectId">
              <el-input v-model="form.subjectNo" placeholder="请输入任务名称" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="subjectName">
              <el-input v-model="form.subjectName" placeholder="请输入任务名称" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="立项时间" prop="fireDate">
              <el-date-picker clearable
                              v-model="form.ddate"
                              type="date"
                              disabled
                              value-format="yyyy-MM-dd"
                              placeholder="请选择立项时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="描述" prop="desp">
              <el-input v-model="form.desp" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="立项时间" prop="fireDate">
              <el-date-picker clearable
                              v-model="form.fireDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择立项时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成时间" prop="demandDate">
              <el-date-picker clearable
                              v-model="form.demandDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择要求完成时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="负责人" prop="headUser">
              <el-card>
                搜索:<el-select
                v-model="form.headUserVal"
                filterable
                remote
                @change="addHeadUser"
                reserve-keyword
                placeholder="请输入负责人"
                :remote-method="findAllUsers"
                :loading="loading">
                <el-option
                  v-for="item in userList"
                  :key="item.userName"
                  :label="item.nickName"
                  :value="item.userName">
                </el-option>
              </el-select>
                <el-divider/>
                <el-tag effect="plain"
                        :disable-transitions="false"
                        closable
                        :key="index"
                        @close="subHeadUser(index)"
                        v-for="(item,index) in form.headUsers">
                  {{item.nickName}}
                </el-tag>
              </el-card>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抄送人" prop="copyUser">
              <el-card>
                搜索:<el-select
                v-model="form.copyUserVal"
                filterable
                remote
                @change="addCopyUser"
                reserve-keyword
                placeholder="请输入抄送人"
                :remote-method="findAllUsers"
                :loading="loading">
                <el-option
                  v-for="item in userList"
                  :key="item.userName"
                  :label="item.nickName"
                  :value="item.userName">
                </el-option>
              </el-select>
                <el-divider/>
                <el-tag effect="plain"
                        closable
                        :key="index"
                        :disable-transitions="false"
                        @close="subCopyUsers(index)"
                        v-for="(item,index) in form.copyUsers">
                  {{item.nickName}}
                </el-tag>
              </el-card>

            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-drawer
      :destroy-on-close="true"
      :visible.sync="drawer" size="60%">
      <h4 class="form-header h4">项目信息</h4>
      <el-descriptions border>
        <el-descriptions-item label="项目编号">{{subform.subjectNo }}</el-descriptions-item>
        <el-descriptions-item label="项目名称">{{subform.subjectName}}</el-descriptions-item>
        <el-descriptions-item label="任务名称">{{ subform.taskName }}</el-descriptions-item>
        <el-descriptions-item label="立项时间">{{ subform.fireDate }}</el-descriptions-item>
        <el-descriptions-item label="项目状态">
          <el-tag size="small" type="success">{{subform.status}}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ subform.demandDate }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{subform.desp}}</el-descriptions-item>
      </el-descriptions>

      <h4 class="form-header h4">任务处理</h4>
      <el-timeline>
        <el-timeline-item :timestamp="item.createTime" placement="top" v-for="(item,index) in processLogs" :key="index">
          <el-card>
            <el-progress :text-inside="true" :stroke-width="26" :percentage="item.rate" status="success"></el-progress>
            <div style="display: flex;justify-content: space-between">
              <div>
                <span style="color: gray">开始:</span><span>{{item.beginDate}}</span>
              </div>
              <div>
                <span style="color: #888787">结束:</span><span>{{item.beginDate}}</span>
              </div>
            </div>
            <el-divider></el-divider>
            <el-row>
              <strong style="font-size: medium">{{item.createName}}:  </strong><span style="color: #888787">{{item.desp}}</span>
            </el-row>
          </el-card>
        </el-timeline-item>

        <el-timeline-item v-if="drawer&&(!canEdit(subform))" :timestamp="parseTime(new Date(), '{y}-{m}-{d}')" placement="top" >
          <el-card>
            <div slot="header" class="clearfix">
              <span>汇报处理进度-{{parseTime(new Date(), '{y}-{m}-{d}')}}</span>
            </div>
            <el-form label-width="100px" ref="processForm" :model="processForm" :rules="processRules" >
              <el-row :gutter="24">
                <el-col :span="7">
                  <el-form-item prop="rate" >
                    <el-progress type="dashboard" :percentage="percentage" :color="colors" ></el-progress>
                    <el-button-group style="display: flex;width: 150px">
                      <el-button icon="el-icon-minus" @click="decrease"></el-button>
                      <el-input-number v-model="percentage" :min="0" :max="100" placeholder="项目进度" :controls="false"/>
                      <el-button icon="el-icon-plus" @click="increase"></el-button>
                    </el-button-group>
                  </el-form-item>
                </el-col>
                <el-col :span="15">
                  <el-form-item label="描述" prop="desp">
                    <el-input v-model="processForm.desp" type="textarea" placeholder="请输入内容" :rows="4"/>
                  </el-form-item>
                  <el-form-item label="执行周期" prop="tdate">
                    <el-date-picker
                      v-model="processForm.tdate"
                      type="daterange"
                      :default-time="['00:00:00', '23:59:59']"
                      value-format="yyyy-MM-dd"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item style="text-align: center;margin-left:-120px;margin-top:30px;">
                <el-button type="primary" @click="submitProcessForm()">提交</el-button>
                <el-button @click="drawer = false ">返回</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-drawer>
  </div>
</template>

<script>
import { listTaskTemp, getTaskTemp, delTaskTemp, addTaskTemp, updateTaskTemp } from "@/api/system/taskTemp";
import { getSubject, updateSubject } from '@/api/system/subject'
import { parseTime } from '@/utils/ruoyi'
import { addProcess, findAllBySubjectId, findAllByTaskId } from '@/api/system/process'
import { listUser } from '@/api/system/user'
import user from '@/store/modules/user'
import { getSubjectTemp } from '@/api/system/subjectTemp'

export default {
  name: "Task",
  data() {
    return {
      // 按钮loading
      yUsername:user.state.name,
      percentage:50,
      buttonLoading: false,
      subject:{},
      drawer : false,
      subform: {},
      processLogs:[],
      userList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务管理表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ddate: undefined,
        taskName: undefined,
        desp: undefined,
        fireDate: undefined,
        demandDate: undefined,
        status: undefined,
        headUser: undefined,
        copyUser: undefined
      },
      colors: [
        {color: '#f56c6c', percentage: 20},
        {color: '#e6a23c', percentage: 40},
        {color: '#5cb87a', percentage: 60},
        {color: '#1989fa', percentage: 80},
        {color: '#6f7ad3', percentage: 100}
      ],
      // 表单参数
      form: {},
      processForm:{
        // ddate:parseTime()(new Date(), '{y}-{m}-{d}')
      },
      // 表单校验
      rules: {
        ddate: [
          { required: true, message: "任务时间不能为空", trigger: "blur" }
        ],
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        desp: [
          { required: true, message: "描述不能为空", trigger: "blur" }
        ],
        fireDate: [
          { required: true, message: "立项时间不能为空", trigger: "blur" }
        ],
        demandDate: [
          { required: true, message: "要求完成时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "任务状态不能为空", trigger: "change" }
        ]
      },
      processRules:{
        desp: [
          { required: true, message: "描述不能为空", trigger: "blur" }
        ],
        tdate: [
          { required: true, message: "开始时间时间不能为空", trigger: "blur" }
        ],
        // beginDate: [
        //   { required: true, message: "开始时间时间不能为空", trigger: "blur" }
        // ],
        // pfinishDate: [
        //   { required: true, message: "计划完成时间不能为空", trigger: "blur" }
        // ],
      }
    };
  },
  created() {
    const subjectId = this.$route.params && this.$route.params.id;
    if (subjectId) {
      this.getSubjectById(subjectId)
      this.queryParams.subjectId = subjectId;
    }
    this.getList();
  },
  methods: {
    /** 查询任务管理列表 */
    getList() {
      this.loading = true;
      listTaskTemp(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getSubjectById(subjectId) {
      this.loading = true;
      getSubjectTemp(subjectId).then(response => {
        this.subject = response.data;
        this.loading = false;
      });
    },
    openDrawer(row){
      this.getProcessLogs(row.taskId);
      this.drawer = true;
      this.subform = row;
      this.processForm.taskId = row.taskId
      this.processForm.subjectId = this.form.subjectId
      this.processForm.subjectNo = this.form.subjectNo
      this.processForm.subjectName = this.form.subjectName
      this.percentage = row.rate;

      this.processForm.ddate = parseTime(new Date(), '{y}-{m}-{d}')
    },
    getProcessLogs(taskId) {
      this.loading = true;
      findAllByTaskId(taskId).then(response => {
        this.processLogs = response.data
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        taskId: undefined,
        ddate: parseTime(new Date(), '{y}-{m}-{d}'),
        taskName: undefined,
        desp: undefined,
        fireDate: undefined,
        demandDate: undefined,
        status: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        headUser: undefined,
        copyUser: undefined,
        rate:0,
        headUsers: [],
        copyUsers: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.status = "新建"
      this.form.subjectId = this.subject.subjectId
      this.form.subjectNo = this.subject.subjectNo
      this.form.subjectName = this.subject.subjectName
      this.title = "添加任务管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const taskId = row.taskId || this.ids
      getTaskTemp(taskId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改任务管理";
      });
    },
    /** 提交按钮 */
    submitProcessForm() {
      console.log(this.processForm)
      this.$refs["processForm"].validate(valid => {
        if (valid) {
          this.processForm.beginDate = this.processForm.tdate[0]
          this.processForm.pfinishDate = this.processForm.tdate[1]
          this.processForm.rate = this.percentage;
          this.processForm.subjectId = this.subform.subjectId
          this.processForm.subjectNo = this.subform.subjectNo
          this.processForm.subjectName = this.subform.subjectName
          addProcess(this.processForm).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.getProcessLogs(this.subform.taskId);
            this.getList()
          }).finally(() => {
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let strheadUser = "";
          this.form.headUsers.forEach(item=>{
            strheadUser += item.userName+","
          })
          this.form.headUser = strheadUser
          let strCopyUser = "";
          this.form.copyUsers.forEach(item=>{
            strCopyUser += item.userName+","
          })
          this.form.copyUser = strCopyUser
          this.buttonLoading = true;
          if (this.form.taskId != null) {
            this.form.createTime = undefined;
            updateTaskTemp(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addTaskTemp(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId || this.ids;
      this.$modal.confirm('是否确认删除任务管理编号为"' + taskIds + '"的数据项？').then(() => {
        this.loading = true;
        return delTaskTemp(taskIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    },
    increase() {
      this.percentage +=5
      this.percentage += 5;
      if (this.percentage > 100) {
        this.percentage = 100;
      }
    },
    decrease() {
      this.percentage -=5
      if (this.percentage < 0) {
        this.percentage = 0;
      }
    },
    findAllUsers(val){
      const query = {
        pageNum: 1,
        pageSize: 10,
        nickName:val
      }
      listUser(query).then(response => {
        this.userList = response.rows;
      });
    },
    addHeadUser: function(e) {
      console.log(e)
      let users = this.userList.filter(item => {
        return item.userName == e
      });
      console.log(users)
      console.log(this.form.headUsers)
      const headUsers = [...users,...this.form.headUsers]
      this.form.headUsers = headUsers;
    },
    subCopyUsers:function(e){
      const users = [...this.form.copyUsers]
      users.splice(e,1)
      this.form.copyUsers = users;
    },
    subHeadUser: function(e) {
      const users = [...this.form.headUsers]
      users.splice(e,1)
      this.form.headUsers = users;
    },
    addCopyUser: function(e) {
      let users = this.userList.filter(item => {
        return item.userName == e
      });
      const copyUsers = [...users,...this.form.copyUsers]
      this.form.copyUsers = copyUsers;
    },
    updStatus(row,status){
      this.$modal.confirm('是否确认更改项目状态为"' + status + '"？').then(() => {
        this.loading = true;
        row.status = status;
        row.createTime = undefined;
        updateTaskTemp(row).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        }).finally(() => {
          this.buttonLoading = false;
        });
      })
    },
    canEdit(obj){
      if(this.yUsername == 'admin'){
        return false;
      }
      return !(obj.createBy == this.yUsername || obj.headUser.indexOf(this.yUsername+',') > -1);
    }
  }
};
</script>
